const speechService = require('../services/azure/speechService');

const pronunciationController = {
    // 脚本朗读评估
    async assessScripted(req, res) {
        try {
            if (!req.file) {
                return res.status(400).json({
                    success: false,
                    message: 'No audio file provided'
                });
            }

            if (!req.body.referenceText) {
                return res.status(400).json({
                    success: false,
                    message: 'Reference text is required for scripted assessment'
                });
            }

            // 获取用户ID（从认证中间件获取）
            const userId = req.user?.userId || req.user?.id;
            if (!userId) {
                return res.status(400).json({
                    success: false,
                    message: 'User ID not found'
                });
            }
            console.log('User ID for assessment:', userId);

            const result = await speechService.assessAndStore(
                userId,
                req.file,
                req.body.referenceText
            );

            return res.json(result);

        } catch (error) {
            console.error('Pronunciation Assessment Error:', error);
            
            return res.status(error.status || 500).json({
                success: false,
                message: error.message || 'Failed to process pronunciation assessment',
                details: error.details || null
            });
        }
    },

    // 自由说话评估
    async assessFree(req, res) {
        try {
            if (!req.file) {
                return res.status(400).json({
                    success: false,
                    message: 'No audio file provided'
                });
            }

            // 获取用户ID（从认证中间件获取，或从请求体中获取，方便测试）
            const userId = req.body.userId || req.user?.userId || req.user?.id || 1;
            console.log('User ID for free assessment:', userId);

            const result = await speechService.assessAndStore(
                userId,
                req.file
            );

            return res.json({
                success: true,
                data: result
            });

        } catch (error) {
            console.error('Pronunciation Assessment Error:', error);
            
            // 返回适当的错误响应
            return res.status(error.status || 500).json({
                success: false,
                message: error.message || 'Failed to process pronunciation assessment',
                details: error.details || null
            });
        }
    },

    // 获取评估历史
    async getHistory(req, res) {
        try {
            const { page = 1, limit = 10 } = req.query;
            const offset = (page - 1) * limit;
            const userId = req.user.userId;

            const [assessments, [totalCount]] = await Promise.all([
                mysql.query(
                    'SELECT * FROM pronunciation_assessments WHERE user_id = ? ORDER BY created_at DESC LIMIT ? OFFSET ?',
                    [userId, parseInt(limit), offset]
                ),
                mysql.query(
                    'SELECT COUNT(*) as total FROM pronunciation_assessments WHERE user_id = ?',
                    [userId]
                )
            ]);

            res.json({
                success: true,
                data: {
                    items: assessments,
                    pagination: {
                        total: totalCount.total,
                        page: parseInt(page),
                        limit: parseInt(limit)
                    }
                }
            });

        } catch (error) {
            console.error('Get History Error:', error);
            res.status(500).json({
                success: false,
                message: 'Failed to get assessment history'
            });
        }
    },

    // 获取评估详情
    async getAssessmentDetails(req, res) {
        try {
            const { assessmentId } = req.params;
            const userId = req.user.userId;

            const [[assessment], details] = await Promise.all([
                mysql.query(
                    'SELECT * FROM pronunciation_assessments WHERE assessment_id = ? AND user_id = ?',
                    [assessmentId, userId]
                ),
                mysql.query(
                    'SELECT * FROM pronunciation_assessment_details WHERE assessment_id = ?',
                    [assessmentId]
                )
            ]);

            if (!assessment) {
                return res.status(404).json({
                    success: false,
                    message: 'Assessment not found'
                });
            }

            res.json({
                success: true,
                data: {
                    assessment,
                    details
                }
            });

        } catch (error) {
            console.error('Get Assessment Details Error:', error);
            res.status(500).json({
                success: false,
                message: 'Failed to get assessment details'
            });
        }
    }
};

module.exports = pronunciationController; 